<?php

declare(strict_types=1);

namespace app\sys\service;

use think\admin\extend\CodeExtend;
use think\admin\model\SysMerchant;
use think\admin\model\SysRelation;
use think\admin\Service;

/**
 * 组织及人之间关联关系
 * Class orgRelation
 * @package app\system\service
 */
class orgRelation extends Service
{
    /**
     * 前台用户全新注册无商户情况下写入的服务
     * @param array $user
     * @param string|null $merchantId
     * @return bool
     */
    public static function frontDeskRegistrationRelation(array $user, ?string $merchantId): bool
    {
        if (empty($user)) return false;
        if (!$merchantId) {
            $merchantData = [
                'merchant_id' => CodeExtend::snId(),
                'merchant_code' => CodeExtend::uniqidNumber(14, '10'),
                'name' => isset($user['companyName']) && $user['companyName'] != '' ? $user['companyName'] : $user['name'],
                'auth_status' => 'NOT_AUTH'
            ];
            SysMerchant::mk()->insert($merchantData);//写入商户信息
        }
        $roleHasUserData = [ //写入角色与用户关系
            'category' => 'SYS_ROLE_HAS_USER',
            'object_id' => '10002',//10002为商户大管理员
            'target_id' => $user['id'],
        ];
        $userHasMerchantData[] = [ //写入用户与商户的关系
            'category' => 'SYS_USER_HAS_MERCHANT',
            'object_id' => $user['id'],
            'target_id' => !$merchantId ? $merchantData['merchant_id'] : $merchantId,
            'ext_json' => !$merchantId ? json_encode($merchantData, JSON_UNESCAPED_UNICODE) : ''
        ];
        $data = [$roleHasUserData, $userHasMerchantData];
        if (SysRelation::mk()->insertAll($data)) {
            return true;
        } else {
            return false;
        }
    }
}